<template>
	<view :class="['content',toggleTheme()]">
		<view class="login-form" v-if="!rPw">
			<view style="margin-bottom: 1rem;">
				<!-- <text class="login-title">{{title}}</text> -->
				<image style="height: 46rpx;width:188rpx ;" :src="titleImgMer" mode=""
					v-if="useUserStore().userType==4"></image>
				<image style="height: 46rpx;width:188rpx ;" :src="titleImgAgent" mode="" v-else></image>
			</view>
			<view class="m-b-12">
				<u-row gutter="0">
					<u-col span="6">
						<text :style="labelStyle">{{subTitle}}</text>
					</u-col>
				</u-row>
			</view>
			<u-form :model="loginForm" ref="loginFormRef" :border-bottom='false' label-position='top'
				:label-style="labelStyle">
				<u-row gutter="16">
					<u-col span="12">
						<u-form-item label="用户名" prop="loginName">
							<u-input v-model="loginForm.loginName" placeholder="请输入用户名" />
						</u-form-item>
					</u-col>
					<!-- <u-col span="12">
						<u-form-item label="密码" prop="pwd">
							<u-input v-model="loginForm.pwd" border type='password' :password-icon='true' />
						</u-form-item>
					</u-col> -->
					<u-col span="7">
						<u-form-item label="验证码" prop="sum">
							<u-input v-model="loginForm.sum" placeholder="请输入验证码" />
						</u-form-item>
					</u-col>
					<u-col span="5">
						<u-form-item label="　" prop="intro">
							<view class="" style="border-radius: 16rpx; overflow: hidden;">
								<u-image height="96rpx" width="240rpx" :src="captchaBase64Image"
									@click="getCaptcha"></u-image>
							</view>
						</u-form-item>
					</u-col>
					<u-col span="12">
						<view class="flex justify-between p-t-6">
							<text :style="labelStyle">短信验证码 (有效期5分钟)</text>
							<view class="">
								<text :style="labelStyle" v-if="remainingTime > 0">倒计时{{ timeval }}</text>
								<text class="warning-color" @click="textingFn" v-else>
									获取短信验证码
								</text>
							</view>
						</view>
					</u-col>
					<u-col span="12">
						<u-form-item label="" prop="code">
							<u-message-input @change="change" @finish="finish" :breathe="true" maxlength=6
								:active-color='useUserStore().userType==2?"#2C5DEB":"#00807D"'
								:value="loginForm.code"></u-message-input>
						</u-form-item>
					</u-col>
				</u-row>
			</u-form>
			<u-row gutter="0">
				<u-col span="12">
					<u-button @click="onLogin" size='medium' class="submit">验证</u-button>
				</u-col>
			</u-row>
		</view>
		<view class="login-form" v-else>
			<view style="margin-bottom: 1rem;">
				<text class="login-title">{{title}}</text>
			</view>
			<u-row gutter="0">
				<u-col span="6">
					<text :style="labelStyle">{{subTitle}}</text>
				</u-col>
			</u-row>
			<u-form :model="rPwdForm" ref="rPwdFormRef" :border-bottom='false' label-position='top'
				:label-style="labelStyle">
				<u-row gutter="16">
					<u-col span="12">
						<u-form-item label="用户名" prop="loginName">
							<u-input v-model="rPwdForm.loginName" placeholder="请输入用户名" />
						</u-form-item>
					</u-col>
					<u-col span="12">
						<u-form-item label="密码" prop="newPassword">
							<u-input v-model="rPwdForm.newPassword" type='password' placeholder="请输入密码：至少三种字符，最小 8 位"
								:password-icon='true' />
						</u-form-item>
					</u-col>
					<u-col span="12">
						<u-form-item label="确认密码" prop="newPasswordAgain">
							<u-input v-model="rPwdForm.newPasswordAgain" type='password' placeholder="请输入新密码"
								:password-icon='true' />
						</u-form-item>
					</u-col>
				</u-row>
			</u-form>
			<u-row gutter="0">
				<u-col span="12">
					<u-button @click="ok" size='medium' class="submit">确认</u-button>
				</u-col>
			</u-row>
		</view>
		<!-- <view class="foot">
			<foot-box></foot-box>
		</view> -->
		<!-- <u-image width="300rpx" height="300rpx" :src="src[0]"></u-image> -->
		<u-toast ref="uToast1" />
	</view>
</template>

<script setup>
	import {
		toggleTheme
	} from '@/stores/themeStore.js';
	import {
		reactive,
		toRefs,
		ref,
		computed,
		getCurrentInstance,
		nextTick
	} from 'vue'
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app'
	import footBox from '@/components/foot-box/index.vue'
	import {
		useUserStore
	} from '@/stores/user.js'
	import {
		loginApi
	} from '@/common/api/login/index.js'
	import {
		selectDictLabel,
		formatTime,
		cloneDeep
	} from '@/common/common.js'
	import {
		ZZB_USER_TYPE_MOBILE
	} from '@/common/dict'
	import {
		useCommonStore
	} from '@/stores/common.js'
	import {
		isMulPassword
	} from '@/common/validate'
	const commonStore = useCommonStore()
	const {
		proxy
	} = getCurrentInstance()

	const uToast1 = ref(null)

	const labelStyle = ref({
		fontSize: '28rpx',
		color: 'rgba(153, 153, 153, 1)'
	})
	const captchaBase64Image = ref('')
	const infoForm = {
		userType: 2,
		loginName: undefined,
		newPassword: undefined,
		newPasswordAgain: undefined,
		sum: undefined,
		code: undefined,
		captchaUuid: undefined,
		token: undefined,
	}
	const loginFormRef = ref()
	const loginForm = ref(infoForm)
	const rules = ref({
		userType: [{
			required: true,
			message: '用户类型不能为空',
			trigger: ['change', 'blur']
		}],
		loginName: [{
			required: true,
			message: '用户名不能为空',
			trigger: ['change', 'blur']
		}],
		pwd: [{
			required: true,
			message: '密码不能为空',
			trigger: ['change', 'blur']
		}],
		sum: [{
			required: true,
			message: '验证码不能为空',
			trigger: ['change', 'blur']
		}],
		code: [{
			required: true,
			message: '验证码不能为空',
			trigger: ['change', 'blur']
		}],
	})

	const title = computed(() => {
		return '忘记密码'
	})
	const subTitle = computed(() => {
		return selectDictLabel(ZZB_USER_TYPE_MOBILE, useUserStore().userType)
	})
	const titleImgMer = '/static/images/mer_forget.svg'
	const titleImgAgent = '/static/images/agent_forget.svg'

	// 验证码
	async function getCaptcha() {
		try {
			let captchaResult = await loginApi.getCaptcha()
			captchaBase64Image.value = captchaResult.data.captchaBase64Image
			loginForm.value.captchaUuid = captchaResult.data.captchaUuid
		} catch (e) {
			console.log('e==>', e)
		}
	}

	const rPw = ref(false)
	const rPwdFormRef = ref()
	const rPwdForm = ref(cloneDeep(infoForm))
	const rulesPw = ref({
		userType: [{
			required: true,
			message: '用户类型不能为空',
			trigger: ['change', 'blur']
		}],
		loginName: [{
			required: true,
			message: '用户名不能为空',
			trigger: ['change', 'blur']
		}],
		newPassword: [{
				required: true,
				message: '密码不能为空',
				trigger: ['change', 'blur']
			},
			{
				validator: isMulPassword,
			},
		],
		newPasswordAgain: [{
				required: true,
				message: '密码不能为空',
				trigger: ['change', 'blur']
			},
			{
				validator: isMulPassword,
			},
		],
	})
	// 登录
	async function onLogin() {
		loginFormRef.value.validate(async (valid) => {
			if (!valid) return
			try {
				const res = await loginApi.verifySmsCode(loginForm.value)
				if (res.code !== 200) return
				rPw.value = true
				rPwdForm.value.loginName = loginForm.value.loginName
				rPwdForm.value.userType = loginForm.value.userType
				rPwdForm.value.token = res.data.token

			} catch (e) {
				loginForm.value.sum = ''
			} finally {
				getCaptcha()
			}
		})
	}
	//确认修改密码
	async function ok() {
		rPwdFormRef.value.validate(async (valid) => {
			if (!valid) return
			try {
				if (rPwdForm.value.newPasswordAgain !== rPwdForm.value.newPassword) {
					uToast1.value.show({
						title: '新密码与确认密码不一致',
						type: 'error'
					})
					return
				}
				const res = await loginApi.resetPassword(rPwdForm.value)
				if (res.code !== 200) {
					uToast1.value.show({
						title: res.message,
						type: 'error'
					})
					return
				}
				uToast1.value.show({
					title: '修改成功',
					type: 'success'
				})
				proxy.$System.goTo('/pages/login/index', {}, {
					method: 'reLaunch'
				})
			} catch (e) {
				console.log(e)
			} finally {}

		})
	}

	/* 倒计时 */
	const TIME = 90
	const remainingTime = ref(0)
	const timer = ref(null) //定时器
	const timeval = computed(() => {
		let val = 0
		if (Number(remainingTime.value) >= 0) {
			val = formatTime(remainingTime.value)
		}
		return val
	})

	function startCountdown() {
		remainingTime.value = TIME
		timer.value = setInterval(() => {
			if (remainingTime.value > 0) {
				remainingTime.value--
			} else {
				clearInterval(timer.value)
			}
		}, 1000)
	}
	/* 短信验证码 */
	const textingFn = async () => {
		if (proxy.$System.isEmpty(loginForm.value.loginName) || proxy.$System.isEmpty(loginForm.value.sum)) {
			uni.showModal({
				content: '用户名和验证码不能为空',
				showCancel: false,
			})
			return
		}
		try {
			const res = await loginApi.getSmsCode(loginForm.value)
			// stopRefreshCaptchaInterval()
			if (res.code !== 200) return
			uToast1.value.show({
				title: '发送验证码成功',
				type: 'success'
			})
			startCountdown()
		} catch (e) {
			if (e.data && e.data.code !== 0) {
				loginForm.value.sum = ''
			}
			console.log(e)
		} finally {
			getCaptcha()
		}
	}
	/* 短信验证码 */

	function change(e) {
		console.log('内容改变，当前值为：' + e);
	}

	function finish(e) {
		console.log('输入结束，当前值为：' + e);
		loginForm.value.code = e
	}

	onLoad((option) => {
		uni.setNavigationBarColor({
			frontColor: '#000000', // 导航栏标题颜色，只能是'black'或'white'
			backgroundColor: '#f0f7ff' // 导航栏背景颜色
		});
	})
	onReady(() => {
		getCaptcha()
		console.log('===', proxy.$System.getEnv());
		nextTick(() => {
			loginFormRef.value?.setRules(rules.value);
		})
		nextTick(() => {
			rPwdFormRef.value?.setRules(rulesPw.value);
		})
	})
</script>

<style>
	page {
		background: linear-gradient(180deg, rgba(240, 247, 255, 1) 0%, rgba(246, 247, 248, 1) 100%) !important;
	}
</style>
<style scoped>
	page {
		background-color: rgb(245, 247, 249) !important;
	}

	.content {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	.login-form {
		flex-grow: 1;
	}

	.login-form :deep(.u-input) {
		background-color: #ffffff !important;
		padding: 12rpx !important;
		border-radius: 16rpx;
	}

	.login-form :deep(.u-form-item) {
		padding: 10rpx 0;
	}

	.login-title {
		color: var(--maiColor);
		font-size: 48rpx;
		font-weight: 600;
	}

	:deep(.u-radio__icon-wrap--checked),
	:deep(.u-checkbox__icon-wrap--checked) {
		background-color: var(--maiColor) !important;
		border-color: var(--maiColor) !important;
	}

	.submit :deep(.u-btn),
	.submit.u-btn {
		margin-top: 20rpx;
		width: 100% !important;
		background-color: var(--maiColor) !important;
		color: #ffffff !important;
	}

	.submit :deep(.u-btn--default--disabled),
	.submit.u-btn--default--disabled {
		opacity: 0.6;
	}

	.wjmm {
		margin-top: .5rem;
	}
</style>